using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SFS.SampleApp.Web.Mvc.Models.Products;
using SFS.SampleApp.BR;
using System.Web.Script.Serialization;
using SFS.SampleApp.Web.Mvc.Models;
using SFS.SampleApp.Web.Mvc.Resources;
using BO = SFS.SampleApp.BusinessObjects;
using SFSdotNet.Framework.Web.Mvc.Security;
using SFSdotNet.Framework.Web.Mvc;
using SFSdotNet.Framework.Web.Mvc.Models;
using SFSdotNet.Framework.Web.Mvc.Resources;
using SFSdotNet.Framework.Web.Mvc.Controllers;
using MvcSiteMapProvider;
using System.Web.Routing;
//using SFS.SampleApp.BusinessObjects;
namespace SFS.SampleApp.Web.Mvc.Controllers
{
    public partial class ProductsController : SFSdotNet.Framework.Web.Mvc.ControllerBase
    {
        private RouteValueDictionary GetRouteData() {
            var popupextra = new RouteValueDictionary();

            foreach (var qs in Request.QueryString.AllKeys)
            {
                List<KeyValuePair<string, string>> extraparams = new List<KeyValuePair<string, string>>();

                if (!string.IsNullOrEmpty(Request.QueryString[qs]))
                {
                    popupextra.Add(qs, Request.QueryString[qs]);

                }
            }
            
            return popupextra;
        }


	#region partial methods
        ControllerEventArgs<Models.Products.ProductModel> e = null;
        partial void OnValidating(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnCreating(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnCreated(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnEditing(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnEdited(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnDeleting(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnDeleted(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
    	partial void OnShowing(object sender, MyEventArgs<UIModel<Models.Products.ProductModel>> e);
    	partial void OnGettingByKey(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
        partial void OnTaken(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
       	partial void OnCreateShowing(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
		partial void OnEditShowing(object sender, ControllerEventArgs<Models.Products.ProductModel> e);
 		partial void OnActionsCreated(object sender, MyEventArgs<UIModel<Models.Products.ProductModel >> e);
		partial void OnCustomActionExecuting(object sender, MyEventArgs<ContextActionModel<Models.Products.ProductModel>> e);
        partial void OnDownloading(object sender, MyEventArgs<ContextActionModel<Models.Products.ProductModel>> e);
      	partial void OnAuthorization(object sender, AuthorizationContext context);

	#endregion
#region Validation methods	
	    private void Validations(ProductModel model) { 
            #region Remote validations

            #endregion
		}

#endregion
		
 		public AuthorizationContext Authorization(AuthorizationContext context)
        {
            OnAuthorization(this,  context );
            return context ;
        }
		public List<ProductModel> GetAll() {
            			var bos = BR.ProductsBR.Instance.GetBy("",
					new SFSdotNet.Framework.My.ContextRequest()
					{
						CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
						{
							OrderBy = "Name",
							SortDirection = SFSdotNet.Framework.Data.SortDirection.Ascending
						}
					});
            			List<ProductModel> results = new List<ProductModel>();
            ProductModel model = null;
            foreach (var bo in bos)
            {
                model = new ProductModel();
                model.Bind(bo);
                results.Add(model);
            }
            return results;

        }
        //
        // GET: /Products/
		[MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		public ActionResult Index()
        {
    		var uiModel = GetContextModel(UIModelContextTypes.ListForm, null);
			
			uiModel.FilterStart = (string)ViewData["startFilter"];
                    MyEventArgs<UIModel<ProductModel>> me = null;

            OnActionsCreated(this, me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel });

            if (me != null)
            {
                uiModel = me.Object;
            }
            if (me == null)
                me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel };
           
            Showing(ref uiModel);
            ViewData["startFilter"] = uiModel.FilterStart;


            return View("ListGen");
        }
		[MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		public ActionResult ListViewGen()
        {
			ViewData["idTab"] = Request.QueryString["idTab"]; 
		 	ViewData["detpop"] = true; // details in popup
            if (!string.IsNullOrEmpty(Request.QueryString["fk"])) {
                ViewData["fk"] = Request.QueryString["fk"]; 
            }
			if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
            {
                ViewData["fkValue"] = Request.QueryString["fkValue"];
            }
			if (!string.IsNullOrEmpty(Request.QueryString["startFilter"]))
            {
                ViewData["startFilter"] = Request.QueryString["startFilter"];
            }
			
			UIModel<ProductModel> uiModel = GetContextModel(UIModelContextTypes.ListForm, null);

            MyEventArgs<UIModel<ProductModel>> me = null;

            OnActionsCreated(this, me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel });
            if (me == null)
                me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel };
            uiModel.Properties = GetProperties(uiModel);
            uiModel.ContextType = UIModelContextTypes.ListForm;
             uiModel.FilterStart = (string)ViewData["startFilter"];
            Showing(ref uiModel);
            ViewData["startFilter"] = uiModel.FilterStart;
            return View("ListViewGen");
        }
			
		private List<PropertyDefinition> GetProperties(UIModel<ProductModel> uiModel)
            {
                List<PropertyDefinition> results = new List<PropertyDefinition>();
			string idProduct = "";
			if (this.Request.RequestContext.RouteData.Values["id"] != null){
				idProduct = SFSdotNet.Framework.Entities.Utils.GetPropertyKey(this.Request.RequestContext.RouteData.Values["id"].ToString().Replace("-","/"), "ProductID");
			}
			bool visibleProperty = true;	
			 bool conditionalshow =false;
                if (uiModel.ContextType == UIModelContextTypes.EditForm || uiModel.ContextType == UIModelContextTypes.DisplayForm ||  uiModel.ContextType == UIModelContextTypes.GenericForm )
                    conditionalshow = true;
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "Name")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "Name",
                    SortBy = "Name",
					
                    TypeName = "String",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.NAME
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "ProductNumber")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "ProductNumber",
                    SortBy = "ProductNumber",
					
                    TypeName = "String",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.PRODUCTNUMBER
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "Color")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "Color",
                    SortBy = "Color",
					
                    TypeName = "String",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.COLOR
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "StandardCost")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "StandardCost",
                    SortBy = "StandardCost",
					
                    TypeName = "Decimal",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.STANDARDCOST
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "ListPrice")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "ListPrice",
                    SortBy = "ListPrice",
					
                    TypeName = "Decimal",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.LISTPRICE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "Size")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "Size",
                    SortBy = "Size",
					
                    TypeName = "String",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.SIZE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "Weight")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "Weight",
                    SortBy = "Weight",
					
                    TypeName = "Decimal",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.WEIGHT
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "SellStartDate")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "SellStartDate",
                    SortBy = "SellStartDate",
					
                    TypeName = "DateTime",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.SELLSTARTDATE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "SellEndDate")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "SellEndDate",
                    SortBy = "SellEndDate",
					
                    TypeName = "DateTime",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.SELLENDDATE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "DiscontinuedDate")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "DiscontinuedDate",
                    SortBy = "DiscontinuedDate",
					
                    TypeName = "DateTime",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.DISCONTINUEDDATE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "ThumbNailPhoto")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "ThumbNailPhoto",
                    SortBy = "ThumbNailPhoto",
					
                    TypeName = "Binary",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.THUMBNAILPHOTO
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "ThumbnailPhotoFileName")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "ThumbnailPhotoFileName",
                    SortBy = "ThumbnailPhotoFileName",
					
                    TypeName = "String",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.THUMBNAILPHOTOFILENAME
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//Null
		//if (this.Request.QueryString["fk"] != "ModifiedDate")
        //	{
				results.Add(new PropertyDefinition()
                {
													
		//			CustomProperties = customProperties,
                    PropertyName = "ModifiedDate",
                    SortBy = "ModifiedDate",
					
                    TypeName = "DateTime",
                    IsNavigationProperty = false,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/",
                    PropertyDisplayName = Resources.ProductResources.MODIFIEDDATE
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//FK_Product_ProductCategory_ProductCategoryID
		//if (this.Request.QueryString["fk"] != "ProductCategory")
        //	{
				results.Add(new PropertyDefinition()
                {
												
					ModuleKey = "SFSSampleApp",
					BusinessObjectKey = "ProductCategory",
					
					GetMethodName = "GetAll",
					GetMethodParameters = "",
					GetMethodDisplayText ="Name",
					GetMethodDisplayValue = "ProductCategoryID",
					
		//			CustomProperties = customProperties,
                    PropertyName = "ProductCategory",
                    SortBy = "ProductCategory.Name",
					
                    TypeName = "SFSSampleAppModel.ProductCategory",
                    IsNavigationProperty = true,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/ProductCategories",
                    PropertyDisplayName = Resources.ProductResources.PRODUCTCATEGORY
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//FK_Product_ProductModel_ProductModelID
		//if (this.Request.QueryString["fk"] != "ProductModel")
        //	{
				results.Add(new PropertyDefinition()
                {
												
					ModuleKey = "SFSSampleApp",
					BusinessObjectKey = "ProductModel",
					
					GetMethodName = "GetAll",
					GetMethodParameters = "",
					GetMethodDisplayText ="Name",
					GetMethodDisplayValue = "ProductModelID",
					
		//			CustomProperties = customProperties,
                    PropertyName = "ProductModel",
                    SortBy = "ProductModel.Name",
					
                    TypeName = "SFSSampleAppModel.ProductModel",
                    IsNavigationProperty = true,
					IsNavigationPropertyMany = false,
                    PathName = "SFSSampleApp/ProductModels",
                    PropertyDisplayName = Resources.ProductResources.PRODUCTMODEL
                });
		//	}
	
	}
visibleProperty =true;
if (visibleProperty){				
	//FK_SalesOrderDetail_Product_ProductID
		//if (this.Request.QueryString["fk"] != "SalesOrderDetails")
        //	{
				results.Add(new PropertyDefinition()
                {
												
					Link = VirtualPathUtility.ToAbsolute("~/") + "SFSSampleApp/SalesOrderDetails/ListViewGen?pal=False&es=False&pag=20&idTab=SalesOrderDetails&fk=Product&startFilter="+ Url.Encode("Product.ProductID = " + idProduct +"")+ "&fkValue=" + idProduct,
					
		//			CustomProperties = customProperties,
                    PropertyName = "SalesOrderDetails",
                    SortBy = "SalesOrderDetails.SalesOrderID",
					
                    TypeName = "SFSSampleAppModel.SalesOrderDetail",
                    IsNavigationProperty = true,
					IsNavigationPropertyMany = true,
                    PathName = "SFSSampleApp/SalesOrderDetails",
                    PropertyDisplayName = Resources.ProductResources.SALESORDERDETAILS
                });
		//	}
	
	}
					
                
				return results;
            }

			
		
		public List<ProductModel> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params  object[] extraParams)
        {

		var bos = BR.ProductsBR.Instance.GetBy(HttpUtility.UrlDecode(filter), pageSize, page, orderBy, orderDir, extraParams);
            ProductModel model = null;
            List<ProductModel> results = new List<ProductModel>();
            foreach (var item in bos)
            {
                model = new ProductModel();
				model.Bind(item);
				results.Add(model);
            }
            return results;
        }
        [MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		public ContentResult GetByJson(string filter, int? pageSize, int? page, string orderBy, string orderDir)
        {
            var filteredResults = GetBy(HttpUtility.UrlDecode(filter), pageSize, page, orderBy, orderDir);
   			 UIModel<ProductModel> uiModel = GetContextModel(UIModelContextTypes.Items, null);
            uiModel.Items = filteredResults;
            Showing(ref uiModel);
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var jsonString = jsonSerializer.Serialize(uiModel.Items).ToString();
            return Content(jsonString);
        }
			
		public int GetByCount(string filter) {
            return BR.ProductsBR.Instance.GetCount(HttpUtility.UrlDecode(filter));
        }
		[MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		public ActionResult GetByKeyJson(string id)
        {
            return Json(GetByKey(id), JsonRequestBehavior.AllowGet);
        }
		public ProductModel GetByKey(string id) {
			return GetByKey(id, null);
       	}
		 public ProductModel GetByKey(string id, string includes) {
             ProductModel model = null;
            ControllerEventArgs<ProductModel> e = null;
			string objectKey = id.Replace("-","/");
             OnGettingByKey(this, e=  new ControllerEventArgs<ProductModel>() { Id = objectKey  });
             bool cancel = false;
             ProductModel eItem = null;
             if (e != null)
             {
                 cancel = e.Cancel;
                 eItem = e.Item;
             }
			if (cancel == false && eItem == null)
             {
		
			Int32 productID = Convert.ToInt32(SFSdotNet.Framework.Entities.Utils.GetPropertyKey(objectKey, "ProductID"));
            
				model = new ProductModel();
				var bo = BR.ProductsBR.Instance.GetByKey(productID, includes);
				if (bo!=null )
					model.Bind(bo);
			}
             else {
                 model = eItem;
             }
			model.IsNew = false;

            return model;
        }
        // GET: /Products/DetailsGen/5
		[MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		[MvcSiteMapNode(AreaName="SFSSampleApp", Clickable=false, ParentKey = "SFSSampleApp_Product_List")]
        public ActionResult DetailsGen(string id)
        {
			if (SiteMap.CurrentNode != null)
				SiteMap.CurrentNode.Title = ProductResources.ENTITY_PLURAL;
			UIModel<ProductModel> uiModel = GetContextModel(UIModelContextTypes.DisplayForm, GetByKey(id));
			
            MyEventArgs<UIModel<ProductModel>> me = null;

            OnActionsCreated(this, me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel });

            if (me != null) {
                uiModel = me.Object;
            }
			
            Showing(ref uiModel);
            if(!string.IsNullOrEmpty(Request.QueryString["popup"]))
                ViewData["ispopup"] = true;
			
            return View("DisplayGen", uiModel.Items[0]);
        }
		[MyAuthorize("r", "Product",  ControllerType=typeof(ProductsController))]
		public ActionResult DetailsViewGen(string id)
        {
			if(!string.IsNullOrEmpty(Request.QueryString["popup"]))
                ViewData["ispopup"] = true;
 			if (!string.IsNullOrEmpty(Request.QueryString["fk"]))
                ViewData["fk"] = Request.QueryString["fk"];
            if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
                ViewData["fkValue"] = Request.QueryString["fkValue"];
           
        	 var uiModel = GetContextModel(UIModelContextTypes.DisplayForm, GetByKey(id));
            MyEventArgs<UIModel<ProductModel>> me = null;

            OnActionsCreated(this, me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel });

            if (me != null)
            {
                uiModel = me.Object;
            }
            
            Showing(ref uiModel);
            return View("DisplayViewGen", uiModel.Items[0]);
        
        }
        //
        // GET: /Products/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }
        //
        // GET: /Products/CreateGen
		[MyAuthorize("c", "Product",  ControllerType=typeof(ProductsController))]
        public ActionResult CreateGen()
        {
			ProductModel model = new ProductModel();
            model.IsNew = true;
			 var me = GetContextModel(UIModelContextTypes.EditForm, model);

             if (!string.IsNullOrEmpty(Request.QueryString["popup"]))
                 ViewData["ispopup"] = true;
             if (!string.IsNullOrEmpty(Request.QueryString["fk"]))
                 ViewData["fk"] = Request.QueryString["fk"];
             if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
                 ViewData["fkValue"] = Request.QueryString["fkValue"];

            Showing(ref me);

			return View("CreateGen",me.Items[0]);
        } 
			
		 private UIModel<ProductModel> GetContextModel(UIModelContextTypes formMode, ProductModel model) {
            UIModel<ProductModel> me = new UIModel<ProductModel>(true, "Products");
			if (!string.IsNullOrEmpty(Request.QueryString["usemode"]))
				me.UseMode = Request.QueryString["usemode"];
			me.ContextType = formMode ;
            me.Properties = GetProperties(me);
 			#region Buttons
            me.ActionButtons.Add(new ActionModel() { ActionKey = "return", Title = GlobalMessages.RETURN, Url = System.Web.VirtualPathUtility.ToAbsolute("~/") + "SFSSampleApp/Products" });
			if (!this.HttpContext.SkipAuthorization){
				me.SetAction("u", (new SFSdotNet.Framework.Globals.Security.Permission()).IsAllowed("u", "Product", "SFSSampleApp"));
				me.SetAction("c", (new SFSdotNet.Framework.Globals.Security.Permission()).IsAllowed("c", "Product", "SFSSampleApp"));
			
			}else{
				me.SetAction("u", true);
				me.SetAction("c", true);
			}
            #endregion              
         
            switch (formMode)
            {
                case UIModelContextTypes.DisplayForm:
					me.TitleForm = ProductResources.PRODUCTS_DETAILS;
                    me.ActionButtons.First(p => p.ActionKey == "u").Title = GlobalMessages.EDIT;

                    break;
                case UIModelContextTypes.EditForm:
					if (model != null)
                    {
					                        me.ActionButtons.First(p => p.ActionKey == "c").Title = GlobalMessages.SAVE;
						if (model.IsNew ){
							me.TitleForm = ProductResources.PRODUCTS_ADD_NEW;
							me.ActionName = "CreateGen";

						}else{
							me.ActionName = "EditGen";

							me.TitleForm = ProductResources.PRODUCTS_EDIT;
						}
					}
                    break;
                case UIModelContextTypes.FilterFields:
                    break;
                case UIModelContextTypes.GenericForm:
                    break;
                case UIModelContextTypes.Items:
                    break;
                case UIModelContextTypes.ListForm:
					me.PrincipalActionName = "GetByJson";
					me.TitleForm = ProductResources.PRODUCTS_LIST;
                    break;
                default:
                    break;
            }
            
			if (model != null )
            	me.Items.Add(model);
            return me;
        }
		// GET: /Products/CreateViewGen
		[MyAuthorize("c", "Product",  ControllerType=typeof(ProductsController))]
        public ActionResult CreateViewGen()
        {
				ProductModel model = new ProductModel();
            model.IsNew = true;
			e= null;
			OnCreateShowing(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
   			if (e!=null)
				model = e.Item;
			
				
            if(!string.IsNullOrEmpty(Request.QueryString["popup"]))
                ViewData["ispopup"] = true;
            if (!string.IsNullOrEmpty(Request.QueryString["fk"]))
                   ViewData["fk"] = Request.QueryString["fk"];
			if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
                ViewData["fkValue"] = Request.QueryString["fkValue"];
			
      
            var me = GetContextModel(UIModelContextTypes.EditForm, model);

            me.Items.Add(model);
            Showing(ref me);
            return View("EditorViewGen", me.Items[0]);
        }
		private void Showing(ref UIModel<ProductModel> uiModel) {
          	
			MyEventArgs<UIModel<ProductModel>> me = null;
            OnShowing(this, me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel });

            if (me != null)
            {
                uiModel = me.Object;
            }
            if (me == null)
                me = new MyEventArgs<UIModel<ProductModel>>() { Object = uiModel };
            ViewData["UIModel"] = uiModel;

        }
        //
        // POST: /Products/Create
		[MyAuthorize("c", "Product",  ControllerType=typeof(ProductsController))]
        [HttpPost]
		[ValidateInput(false)] 
        public ActionResult CreateGen([Bind(Exclude = "ThumbNailPhoto")]ProductModel  model)
        {
		 	e = null;
			this.Validations(model);

            OnValidating(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
           
		  	if (!ModelState.IsValid) {
				model.IsNew = true;
				var me = GetContextModel(UIModelContextTypes.EditForm, model);
                Showing(ref me);
                 if (!string.IsNullOrEmpty(Request.QueryString["popup"]))
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["popup"]))
                        ViewData["ispopup"] = true;
                    if (!string.IsNullOrEmpty(Request.QueryString["fk"]))
                        ViewData["fk"] = Request.QueryString["fk"];
                    if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
                        ViewData["fkValue"] = Request.QueryString["fkValue"];

                    return View("EditorViewGen", model);
                }
                else
                    return View("CreateGen", model);
            }
            try
            {
	
				// habilitando m�todo parcial
                #region implementaci�n de m�todo parcial
               
                bool cancel = false; bool replaceResult = false;
                OnCreating(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
                if (e != null) {
                    if (e.Cancel && e.ActionResult != null)
                        return e.ActionResult;
                    else if (e.Cancel == true)
                        cancel = true;
                    else if (e.ActionResult != null)
                        replaceResult = true;
                }
                #endregion
                // si fue implementado el m�todo parcial y no se ha decidido suspender la acci�n
                if (!cancel)
                	model.Bind(ProductsBR.Instance.Create(model.GetBusinessObject()));
				OnCreated(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
                 if (e != null )
					if (e.ActionResult != null)
                    	replaceResult = true;		
				if (!replaceResult)
                {
                    if (!string.IsNullOrEmpty(Request.Form["__continue"]))
                    {
                        ViewData["__continue"] = true;
                    }
                    if (!string.IsNullOrEmpty(Request.QueryString["popup"]) || !string.IsNullOrEmpty(Request.Form["popup"]))
                    {
                        if (!string.IsNullOrEmpty(Request.Form["__continue"]))

                        {
                            var popupextra = GetRouteData();
                            popupextra.Add("id", model.SafeKey);
                            return RedirectToAction("EditViewGen", popupextra);
                        }
                        else
                        {
                            return PartialView("ResultMessageView", (new MessageModel()).GetDone(GlobalMessages.ADD_DONE));
                        }
                    }        			if (!string.IsNullOrEmpty(Request.QueryString["ReturnAfter"]))
                        return Redirect(Request.QueryString["ReturnAfter"]);
                    else{
                            if (!string.IsNullOrEmpty(Request.Form["__continue"])) {
                                                   var popupextra = GetRouteData();
                                popupextra.Add("id", model.SafeKey);
                                return RedirectToAction("EditGen", popupextra);

                            }
                            return RedirectToAction("Index");
                        }
						 }
                else {
                    return e.ActionResult;
                    }
				}
            catch
            {
                return View();
            }
        }        
        //
        // GET: /Products/Edit/5 
        public ActionResult Edit(int id)
        {
            return View();
        }
			
		
		[MyAuthorize("u", "Product",  ControllerType=typeof(ProductsController))]
		[MvcSiteMapNode(AreaName="SFSSampleApp", Clickable=false, ParentKey = "SFSSampleApp_Product_List")]
		public ActionResult EditGen(string id)
        {
			if (SiteMap.CurrentNode != null)
				SiteMap.CurrentNode.Title = ProductResources.ENTITY_SINGLE;		 	
  // habilitando m�todo parcial
            #region implementaci�n de m�todo parcial

            bool cancel = false; bool replaceResult = false;
            OnEditShowing(this, e = new ControllerEventArgs<ProductModel>() { Id= id });
            if (e != null)
            {
                if (e.Cancel && e.ActionResult != null)
                    return e.ActionResult;
                else if (e.Cancel == true)
                    cancel = true;
                else if (e.ActionResult != null)
                    replaceResult = true;
            }
            #endregion
            ProductModel model = null;
            // si fue implementado el m�todo parcial y no se ha decidido suspender la acci�n
            if (!cancel)
                model = GetByKey(id);
            else
                model = e.Item;
			 var me = GetContextModel(UIModelContextTypes.EditForm, model);
            Showing(ref me);


            if (!replaceResult)
            {
                 return View("EditGen", me.Items[0]);
            }
            else {
                return e.ActionResult;
            }
        }
			[MyAuthorize("u", "Product",  ControllerType=typeof(ProductsController))]
		public ActionResult EditViewGen(string id)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["popup"]))
                ViewData["ispopup"] = true;
			  if (!string.IsNullOrEmpty(Request.QueryString["fk"]))
                ViewData["fk"] = Request.QueryString["fk"];
            if (!string.IsNullOrEmpty(Request.QueryString["fkValue"]))
                ViewData["fkValue"] = Request.QueryString["fkValue"];

					  // habilitando m�todo parcial
            #region implementaci�n de m�todo parcial

            bool cancel = false; bool replaceResult = false;
            OnEditShowing(this, e = new ControllerEventArgs<ProductModel>() { Id= id });
            if (e != null)
            {
                if (e.Cancel && e.ActionResult != null)
                    return e.ActionResult;
                else if (e.Cancel == true)
                    cancel = true;
                else if (e.ActionResult != null)
                    replaceResult = true;
            }
            #endregion
			
            ProductModel model = null;
            // si fue implementado el método parcial y no se ha decidido suspender la acción
            if (!cancel)
                model = GetByKey(id);
            else
                model = e.Item;
            var me = GetContextModel(UIModelContextTypes.EditForm, model);
            Showing(ref me);

            return View("EditorViewGen", me.Items[0]);
        }
		[MyAuthorize("u", "Product",  ControllerType=typeof(ProductsController))]
		[HttpPost]
		[ValidateInput(false)] 
        public ActionResult EditGen(ProductModel model)
        {
			e = null;
			this.Validations(model);

            OnValidating(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
           
            if (!ModelState.IsValid)
            {
			   	var me = GetContextModel(UIModelContextTypes.EditForm, model);
                Showing(ref me);
			
				if (!string.IsNullOrEmpty(Request.Form["popup"])){
                	ViewData["ispopup"] = true;
					return View("EditorViewGen", model);
				}
				else
					return View("EditGen", model);
            }
            try
            {
			
				// habilitando m�todo parcial
                #region implementaci�n de m�todo parcial
               
                bool cancel = false; bool replaceResult = false;
                OnEditing(this, e = new ControllerEventArgs<ProductModel>() { Item = model });
                if (e != null) {
                    if (e.Cancel && e.ActionResult != null)
                        return e.ActionResult;
                    else if (e.Cancel == true)
                        cancel = true;
                    else if (e.ActionResult != null)
                        replaceResult = true;
                }
                #endregion
                // si fue implementado el m�todo parcial y no se ha decidido suspender la acci�n
                if (!cancel)
                	ProductsBR.Instance.Update(model.GetBusinessObject());

                if (!string.IsNullOrEmpty(Request.QueryString["autosave"]))
                {
                    return Json("ok", JsonRequestBehavior.AllowGet);
                }
                else
                {
				if (!replaceResult)
                {
					if (!string.IsNullOrEmpty(Request.Form["popup"]))
						return PartialView("ResultMessageView", (new MessageModel()).GetDone(GlobalMessages.UPDATE_DONE));
        			if (!string.IsNullOrEmpty(Request.Form["ReturnAfter"]))
                        return Redirect(Request.Form["ReturnAfter"]);
                    else
                        return RedirectToAction("Index", new { usemode = Request.Form["usemode"]});
				 }
                else {
                    return e.ActionResult;
				}
                }		
            }
            catch
            {
                if (!string.IsNullOrEmpty(Request.QueryString["autosave"]))
                {
                    return Json("error", JsonRequestBehavior.AllowGet);
                }
                else {
                    return View();
                }
            }
        }
        //
        // POST: /Products/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                //  Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Products/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }
		[MyAuthorize("d", "Product",  ControllerType=typeof(ProductsController))]
		[HttpDelete]
        public ActionResult DeleteGen(string objectKey, string extraParams)
        {
            try
            {
					
			
				Int32 productID = Convert.ToInt32(SFSdotNet.Framework.Entities.Utils.GetPropertyKey(objectKey.Replace("-", "/"), "ProductID")); 
                BO.Product entity = new BO.Product() { ProductID = productID };

                BR.ProductsBR.Instance.Delete(entity);               
                return PartialView("ResultMessageView", (new MessageModel()).GetDone(GlobalMessages.DELETE_DONE));

            }
            catch(Exception ex)
            {
                if (Request.IsAjaxRequest())
                {
                    string message = GlobalMessages.ERROR_TRY_LATER;
                    if (ex.Data["usermessage"] != null)
                    {
                        message = ex.Data["usermessage"].ToString();
                    }

                    return PartialView("ResultMessageView", (new MessageModel()).GetException(message));
                }
                else
                {
                    return View();
                }
            }
        }
			
		public FileMediaResult Download(string query, bool allSelected, string selected, string orderBy, string direction, string format, string actionKey)
        {
			
            List<Int32> keysSelected1 = new List<Int32>();
            if (!string.IsNullOrEmpty(selected)) {
                foreach (var keyString in selected.Split(char.Parse("|")))
                {
				
                    keysSelected1.Add(Int32.Parse(keyString));
                }
            }
				
            query = SFSdotNet.Framework.Web.Mvc.Lists.GetQuery(query, allSelected, selected, "ProductID");
            MyEventArgs<ContextActionModel<ProductModel>> eArgs = null;
            List<ProductModel> results = GetBy(query, null, null, orderBy, direction, keysSelected1);
            OnDownloading(this, eArgs = new MyEventArgs<ContextActionModel<ProductModel>>() { Object = new ContextActionModel<ProductModel>() { Query = query, SelectedItems = results, Selected=selected, SelectAll = allSelected, Direction = direction , OrderBy = orderBy, ActionKey=actionKey  } });

            if (eArgs != null)
            {
                if (eArgs.Object.Result != null)
                    return (FileMediaResult)eArgs.Object.Result;
            }
            

            return (new FeaturesController()).ExportDownload(typeof(ProductModel), results, format, ProductResources.PRODUCTS_LIST);
            
        }
			
		
		[HttpPost]
        public ActionResult CustomActionExecute(ContextActionModel model) {
		 try
            {
			List<Int32> keysSelected1 = new List<Int32>();
            if (!string.IsNullOrEmpty(model.Selected))
            {
                foreach (var keyString in model.Selected.Split(char.Parse(",")))
                {
				
				keysSelected1.Add(Int32.Parse(keyString.Split(char.Parse("|"))[0]));
                        
                    

			
                }
            }

            model.Query = SFSdotNet.Framework.Web.Mvc.Lists.GetQuery(model.Query , model.SelectAll , model.Selected, "ProductID");
           
			List<ProductModel> results = GetBy(model.Query, null, null, model.OrderBy, model.Direction , keysSelected1);
			#region implementaci�n de m�todo parcial
            bool replaceResult = false;
            MyEventArgs<ContextActionModel<ProductModel>> actionEventArgs = null;
            OnCustomActionExecuting(this, actionEventArgs=new MyEventArgs<ContextActionModel<ProductModel>>() { Object= new ContextActionModel<ProductModel>() { ActionKey= model.ActionKey , Direction = model.Direction, OrderBy = model.OrderBy, SelectedItems = results, SelectedKeys = model.Selected, Query = model.Query } });
            if (model.ActionKey == "deletemany") { 
                // eliminar muchos, como una acci�n custom
                List<BO.Product> entities = new List<BO.Product>();
                foreach (var item in results)
                {
                    entities.Add(item.GetBusinessObject());
                }
                BR.ProductsBR.Instance.Delete(entities);


            }
			
                 if (actionEventArgs == null)
                {
                    if (model.ActionKey != "deletemany"  && model.ActionKey != "deleterelmany")
                    {
                        throw new NotImplementedException("");
                    }
                }
                else
                {
                    replaceResult = actionEventArgs.Object.Result is ActionResult /*actionEventArgs.Object.ReplaceResult*/;
                }
                #endregion
                if (!replaceResult)
                {
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("ResultMessageView", (new MessageModel()).GetDone(GlobalMessages.DONE));
                    }
                    else
                    {
                        return View();
                    }
                }
                else
                {
                    return (ActionResult)actionEventArgs.Object.Result;
                }
            }
            catch (Exception ex)
            {

                if (Request.IsAjaxRequest())
                {
                    string message = GlobalMessages.ERROR_TRY_LATER;
                    if (ex.Data["usermessage"] != null) {
                        message = ex.Data["usermessage"].ToString();
                    }

                    return PartialView("ResultMessageView", (new MessageModel()).GetException(message));
                }
                else
                {
                    return View();
                }

            }
        }
        //
        // POST: /Products/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
			
	
    }
}
